const express = require('express');
const mysql = require('../services/mysql');
const router = express.Router();
const { DateTime } = require('luxon');
const fetch = require('node-fetch');
const binance = require('../services/binance');
const path = require('path');
const pool = mysql.createPool({
    host: '182.160.6.140',
    user: 'root',
    password: 'BinanceRoot2023',
    database: 'binance_klines',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});
const { getBinanceKlines, getBinanceLatestPrice } = require('../services/binance');
const statsCache = require('../services/statsCache');

// 定义时间范围常量
const TIME_RANGES = {
  '1h': { hours: 1 },
  '6h': { hours: 6 },
  '12h': { hours: 12 },
  '1d': { days: 1 },
  '3d': { days: 3 },
  '7d': { days: 7 },
  '14d': { days: 14 },
  '1m': { months: 1 },
  '3m': { months: 3 },
  '6m': { months: 6 },
  '1y': { years: 1 },
  '2y': { years: 2 },
  '3y': { years: 3 },
  '4y': { years: 4 },
  '5y': { years: 5 },
  '6y': { years: 6 },
  '7y': { years: 7 }
};

// 获取K线数据的API
router.get('/api/klines', async (req, res) => {
    try {
        let { symbol, interval, startTime, endTime } = req.query;
        
        // 参数验证
        if (!symbol || !interval) {
            return res.status(400).json({
                error: '缺少必需的参数',
                details: {
                    symbol: symbol ? '已提供' : '缺失',
                    interval: interval ? '已提供' : '缺失'
                }
            });
        }

        // 验证交易对格式
        symbol = symbol.toUpperCase();
        if (!['BTCUSDT', 'ETHUSDT'].includes(symbol)) {
            return res.status(400).json({
                error: '无效的交易对',
                details: {
                    provided: symbol,
                    allowed: ['BTCUSDT', 'ETHUSDT']
                }
            });
        }
        
        // 验证时间间隔
        if (!['5m', '10m', '15m', '30m', '1h', '1d'].includes(interval)) {
            return res.status(400).json({
                error: '无效的时间间隔',
                details: {
                    provided: interval,
                    allowed: ['5m', '10m', '15m', '30m', '1h', '1d']
                }
            });
        }

        // 处理时间参数
        if (!startTime || !endTime) {
            const now = new Date();
            endTime = now.getTime();
            startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
        } else {
            startTime = parseInt(startTime);
            endTime = parseInt(endTime);
            
            if (isNaN(startTime) || isNaN(endTime)) {
                return res.status(400).json({
                    error: '无效的时间格式',
                    details: {
                        startTime: startTime ? '无效格式' : '缺失',
                        endTime: endTime ? '无效格式' : '缺失'
                    }
                });
            }
        }

        // 计算时间范围
        const timeRangeInDays = Math.ceil((endTime - startTime) / (1000 * 60 * 60 * 24));
        console.log(`请求的时间范围: ${timeRangeInDays} 天`);

        // 确定数据源
        const shouldUseCache = timeRangeInDays > 7;
        console.log(`使用数据源: ${shouldUseCache ? '本地缓存' : '币安API'}`);

        // 如果需要使用缓存
        if (shouldUseCache) {
            try {
                const connection = await pool.getConnection();
                try {
                    const actualInterval = interval === '10m' ? '5m' : interval;
                    const [rows] = await connection.query(
                        `SELECT * FROM kline_${actualInterval} 
                         WHERE symbol = ? 
                         AND open_time >= ? 
                         AND open_time <= ? 
                         ORDER BY open_time ASC`,
                        [symbol, startTime, endTime]
                    );

                    if (rows && rows.length > 0) {
                        console.log(`从缓存获取到 ${rows.length} 条数据`);
                        const formattedData = rows.map(row => [
                            row.open_time.toString(),
                            row.open_price.toString(),
                            row.high_price.toString(),
                            row.low_price.toString(),
                            row.close_price.toString(),
                            row.volume.toString(),
                            row.close_time.toString(),
                            row.quote_volume.toString(),
                            row.trades_count.toString(),
                            row.taker_buy_volume.toString(),
                            row.taker_buy_quote_volume.toString()
                        ]);

                        if (interval === '10m') {
                            const mergedData = [];
                            for (let i = 0; i < formattedData.length - 1; i += 2) {
                                if (i + 1 < formattedData.length) {
                                    const k1 = formattedData[i];
                                    const k2 = formattedData[i + 1];
                                    if (parseInt(k2[0]) - parseInt(k1[0]) === 5 * 60 * 1000) {
                                        mergedData.push([
                                            k1[0],
                                            k1[1],
                                            Math.max(parseFloat(k1[2]), parseFloat(k2[2])).toString(),
                                            Math.min(parseFloat(k1[3]), parseFloat(k2[3])).toString(),
                                            k2[4],
                                            (parseFloat(k1[5]) + parseFloat(k2[5])).toString(),
                                            k2[6],
                                            (parseFloat(k1[7]) + parseFloat(k2[7])).toString(),
                                            (parseInt(k1[8]) + parseInt(k2[8])).toString(),
                                            (parseFloat(k1[9]) + parseFloat(k2[9])).toString(),
                                            (parseFloat(k1[10]) + parseFloat(k2[10])).toString()
                                        ]);
                                    }
                                }
                            }
                            return res.json(mergedData);
                        }
                        return res.json(formattedData);
                    }
                } finally {
                    connection.release();
                }
            } catch (dbError) {
                console.error('缓存查询失败:', dbError);
            }
        }

        // 从币安API获取数据
        console.log('从币安API获取数据');
        const actualInterval = interval === '10m' ? '5m' : interval;
        const binanceUrl = `https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=${actualInterval}&startTime=${startTime}&endTime=${endTime}&limit=1000`;
        console.log('币安API URL:', binanceUrl);

        const response = await fetch(binanceUrl, {
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            }
        });

        if (!response.ok) {
            const errorText = await response.text();
            console.error('币安API错误响应:', errorText);
            throw new Error(`币安API返回错误: ${response.status} ${errorText}`);
        }

        const data = await response.json();
        console.log(`从币安API获取到 ${data.length} 条数据`);

        if (interval === '10m') {
            const mergedData = [];
            for (let i = 0; i < data.length - 1; i += 2) {
                if (i + 1 < data.length) {
                    const k1 = data[i];
                    const k2 = data[i + 1];
                    if (parseInt(k2[0]) - parseInt(k1[0]) === 5 * 60 * 1000) {
                        mergedData.push([
                            k1[0],
                            k1[1],
                            Math.max(parseFloat(k1[2]), parseFloat(k2[2])).toString(),
                            Math.min(parseFloat(k1[3]), parseFloat(k2[3])).toString(),
                            k2[4],
                            (parseFloat(k1[5]) + parseFloat(k2[5])).toString(),
                            k2[6],
                            (parseFloat(k1[7]) + parseFloat(k2[7])).toString(),
                            (parseInt(k1[8]) + parseInt(k2[8])).toString(),
                            (parseFloat(k1[9]) + parseFloat(k2[9])).toString(),
                            (parseFloat(k1[10]) + parseFloat(k2[10])).toString()
                        ]);
                    }
                }
            }
            return res.json(mergedData);
        }

        return res.json(data);
    } catch (error) {
        console.error('获取K线数据失败:', error);
        res.status(500).json({
            error: '获取K线数据失败',
            message: error.message
        });
    }
});

// 直接从币安获取K线数据
router.get('/api/binance/klines', async (req, res) => {
    try {
        let { symbol, interval, startTime, endTime } = req.query;
        
        // 记录请求信息
        console.log(`收到币安K线数据请求: symbol=${symbol}, interval=${interval}, startTime=${startTime}(${new Date(parseInt(startTime)).toLocaleString()}), endTime=${endTime}(${new Date(parseInt(endTime)).toLocaleString()})`);
        
        // 参数验证
        if (!symbol || !interval) {
            return res.status(400).json({
                error: '缺少必需的参数',
                details: {
                    symbol: symbol ? '已提供' : '缺失',
                    interval: interval ? '已提供' : '缺失'
                }
            });
        }

        // 验证交易对格式
        symbol = symbol.toUpperCase();
        if (!['BTCUSDT', 'ETHUSDT'].includes(symbol)) {
            return res.status(400).json({
                error: '无效的交易对',
                details: {
                    provided: symbol,
                    allowed: ['BTCUSDT', 'ETHUSDT']
                }
            });
        }

        // 验证时间间隔
        if (!['5m', '10m', '15m', '30m', '1h', '1d'].includes(interval)) {
            return res.status(400).json({
                error: '无效的时间间隔',
                details: {
                    provided: interval,
                    allowed: ['5m', '10m', '15m', '30m', '1h', '1d']
                }
            });
        }

        // 处理时间参数
        if (!startTime || !endTime) {
            const now = new Date();
            endTime = now.getTime();
            startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
            console.log('使用默认时间范围:', new Date(startTime).toLocaleString(), '至', new Date(endTime).toLocaleString());
        } else {
            startTime = parseInt(startTime);
            endTime = parseInt(endTime);
            
            if (isNaN(startTime) || isNaN(endTime)) {
                return res.status(400).json({
                    error: '无效的时间格式',
                    details: {
                        startTime: startTime ? '无效格式' : '缺失',
                        endTime: endTime ? '无效格式' : '缺失'
                    }
                });
            }
            
            console.log('使用提供的时间范围:', new Date(startTime).toLocaleString(), '至', new Date(endTime).toLocaleString());
        }

        // 记录系统当前时间
        console.log('系统当前时间:', new Date().toLocaleString());

        // 使用服务端的币安服务模块获取数据
        console.log('正在通过服务器从币安API获取数据...');
        
        // 处理10m周期的特殊情况
        const actualInterval = interval === '10m' ? '5m' : interval;
        
        // 使用binanceService获取数据
        const data = await binance.getKlines(symbol, actualInterval, 1000, startTime, endTime);
        
        if (!data) {
            throw new Error('无法从币安获取数据');
        }
        
        console.log(`从币安API获取到 ${data.length} 条数据`);
        
        // 打印第一条和最后一条数据的时间戳，用于调试
        if (data.length > 0) {
            console.log('首条数据时间:', new Date(parseInt(data[0][0])).toLocaleString());
            console.log('末条数据时间:', new Date(parseInt(data[data.length-1][0])).toLocaleString());
        }

        if (interval === '10m') {
            const mergedData = [];
            for (let i = 0; i < data.length - 1; i += 2) {
                if (i + 1 < data.length) {
                    const k1 = data[i];
                    const k2 = data[i + 1];
                    if (parseInt(k2[0]) - parseInt(k1[0]) === 5 * 60 * 1000) {
                        mergedData.push([
                            k1[0],
                            k1[1],
                            Math.max(parseFloat(k1[2]), parseFloat(k2[2])).toString(),
                            Math.min(parseFloat(k1[3]), parseFloat(k2[3])).toString(),
                            k2[4],
                            (parseFloat(k1[5]) + parseFloat(k2[5])).toString(),
                            k2[6],
                            (parseFloat(k1[7]) + parseFloat(k2[7])).toString(),
                            (parseInt(k1[8]) + parseInt(k2[8])).toString(),
                            (parseFloat(k1[9]) + parseFloat(k2[9])).toString(),
                            (parseFloat(k1[10]) + parseFloat(k2[10])).toString()
                        ]);
                    }
                }
            }
            console.log(`合并后得到 ${mergedData.length} 条10分钟K线数据`);
            return res.json(mergedData);
        }

        return res.json(data);
    } catch (error) {
        console.error('获取K线数据失败:', error);
        res.status(500).json({
            error: '获取K线数据失败',
            message: error.message
        });
    }
});

// 获取K线页面
router.get('/kline', (req, res) => {
    res.sendFile(path.join(__dirname, '../views/kline.html'));
});

// 获取最新K线数据的API
router.get('/api/latest_kline', async (req, res) => {
    try {
        const { symbol, interval } = req.query;
        
        // 参数验证
        if (!symbol || !interval) {
            return res.status(400).json({ error: '缺少必需参数: symbol和interval是必需的' });
        }
        
        // 验证交易对和时间间隔
        const validSymbols = ['BTCUSDT', 'ETHUSDT'];
        const validIntervals = ['5m', '10m', '15m', '30m', '1h', '1d'];
        
        if (!validSymbols.includes(symbol)) {
            return res.status(400).json({ error: '不支持的交易对' });
        }
        if (!validIntervals.includes(interval)) {
            return res.status(400).json({ error: '不支持的时间间隔' });
        }
        
        // 获取最新的一条K线数据
        const [rows] = await pool.query(
            `SELECT * FROM kline_${interval}_enhanced 
             WHERE symbol = ? 
             ORDER BY open_time DESC 
             LIMIT 1`,
            [symbol]
        );
        
        if (rows.length === 0) {
            return res.status(404).json({ error: '未找到数据' });
        }
        
        res.json(rows[0]);
        
    } catch (error) {
        console.error('获取最新K线数据失败:', error);
        res.status(500).json({ error: '服务器内部错误' });
    }
});

// 获取K线统计数据
router.get('/api/stats', async (req, res) => {
  try {
    const { symbol = 'BTCUSDT', interval = '1d', range = '1m' } = req.query;
    
    // 验证参数
    if (!['BTCUSDT', 'ETHUSDT'].includes(symbol)) {
      return res.status(400).json({ error: '不支持的交易对' });
    }
    
    if (!['1d', '1h', '30m', '15m', '10m', '5m'].includes(interval)) {
      return res.status(400).json({ error: '不支持的时间周期' });
    }
    
    if (!['today', 'yesterday', '1w', '1m', '3m', '6m', '1y', '2y', '3y', '4y', '5y', '6y', '7y'].includes(range)) {
      return res.status(400).json({ error: '不支持的时间范围' });
    }

    console.log(`从缓存获取统计数据: ${symbol}, ${interval}, ${range}`);
    
    // 从缓存获取统计数据
    const stats = await statsCache.getStats(symbol, interval, range);
    
    res.json({
      code: 0,
      data: {
        ...stats,
        timeRange: {
          start: stats.timeRange.start,
          end: stats.timeRange.end,
          range: range
        }
      },
      msg: 'success'
    });
  } catch (error) {
    console.error('获取K线统计数据失败:', error);
    res.status(500).json({
      code: 500,
      msg: '服务器内部错误',
      error: error.message
    });
  }
});

// 获取K线统计数据 - 供前端API调用，新版路径
router.get('/stats-data', async (req, res) => {
  try {
    const { symbol = 'BTCUSDT', interval = '1d', range = '1m' } = req.query;
    
    // 验证参数
    if (!['BTCUSDT', 'ETHUSDT'].includes(symbol)) {
      return res.status(400).json({ error: '不支持的交易对' });
    }
    
    if (!['1d', '1h', '30m', '15m', '10m', '5m'].includes(interval)) {
      return res.status(400).json({ error: '不支持的时间周期' });
    }
    
    if (!['today', 'yesterday', '1w', '1m', '3m', '6m', '1y', '2y', '3y', '4y', '5y', '6y', '7y'].includes(range)) {
      return res.status(400).json({ error: '不支持的时间范围' });
    }

    // 设置响应类型为JSON
    res.setHeader('Content-Type', 'application/json');

    // 如果是today范围，直接从币安API获取当天的实时数据并计算统计结果
    if (range === 'today') {
      console.log(`今天范围，直接从币安API获取实时数据: ${symbol}, ${interval}`);
      
      // 计算今天的开始时间戳
      const now = new Date();
      const startOfDay = new Date(now);
      startOfDay.setHours(0, 0, 0, 0);
      const startTime = startOfDay.getTime();
      const endTime = now.getTime();
      
      console.log(`今天时间范围: ${new Date(startTime).toLocaleString()} 至 ${new Date(endTime).toLocaleString()}`);
      
      try {
        // 从币安API获取今天的K线数据
        const actualInterval = interval === '10m' ? '5m' : interval;
        const binanceKlines = await binance.getKlines(
          symbol, 
          actualInterval,
          null,  // 不限制数量
          startTime,
          endTime
        );
        
        if (!binanceKlines || binanceKlines.length === 0) {
          // 如果币安没有返回今天的数据，返回空结果
          console.log(`币安API未返回今天的数据，返回空结果`);
          return res.json({
            code: 0,
            data: {
              total: 0,
              up: 0,
              down: 0,
              flat: 0,
              consecutive: { up: {}, down: {} },
              timeRange: {
                start: new Date(startTime).toISOString(),
                end: new Date(endTime).toISOString(),
                range: range
              }
            },
            msg: 'success'
          });
        }
        
        console.log(`币安API返回 ${binanceKlines.length} 条今天的数据`);
        
        // 处理10m周期的特殊情况
        let processedKlines = binanceKlines;
        if (interval === '10m') {
          processedKlines = [];
          for (let i = 0; i < binanceKlines.length - 1; i += 2) {
            if (i + 1 < binanceKlines.length) {
              const k1 = binanceKlines[i];
              const k2 = binanceKlines[i + 1];
              if (parseInt(k2[0]) - parseInt(k1[0]) === 5 * 60 * 1000) {
                processedKlines.push([
                  k1[0],
                  k1[1],
                  Math.max(parseFloat(k1[2]), parseFloat(k2[2])).toString(),
                  Math.min(parseFloat(k1[3]), parseFloat(k2[3])).toString(),
                  k2[4],
                  (parseFloat(k1[5]) + parseFloat(k2[5])).toString(),
                  k2[6],
                  (parseFloat(k1[7]) + parseFloat(k2[7])).toString(),
                  (parseInt(k1[8]) + parseInt(k2[8])).toString(),
                  (parseFloat(k1[9]) + parseFloat(k2[9])).toString(),
                  (parseFloat(k1[10]) + parseFloat(k2[10])).toString()
                ]);
              }
            }
          }
          console.log(`合并后得到 ${processedKlines.length} 条10分钟K线数据`);
        }
        
        // 计算统计数据
        let upCount = 0;
        let downCount = 0;
        let flatCount = 0;
        
        for (const kline of processedKlines) {
          const openPrice = parseFloat(kline[1]);
          const closePrice = parseFloat(kline[4]);
          
          if (closePrice > openPrice) {
            upCount++;
          } else if (closePrice < openPrice) {
            downCount++;
          } else {
            flatCount++;
          }
        }
        
        // 计算连续上涨和下跌
        const consecutiveUp = {};
        const consecutiveDown = {};
        
        let currentUpStreak = 0;
        let currentDownStreak = 0;
        
        for (const kline of processedKlines) {
          const openPrice = parseFloat(kline[1]);
          const closePrice = parseFloat(kline[4]);
          
          if (closePrice > openPrice) {
            currentUpStreak++;
            
            if (currentDownStreak > 1) {
              consecutiveDown[currentDownStreak] = (consecutiveDown[currentDownStreak] || 0) + 1;
            }
            currentDownStreak = 0;
          } else if (closePrice < openPrice) {
            currentDownStreak++;
            
            if (currentUpStreak > 1) {
              consecutiveUp[currentUpStreak] = (consecutiveUp[currentUpStreak] || 0) + 1;
            }
            currentUpStreak = 0;
          } else {
            if (currentUpStreak > 1) {
              consecutiveUp[currentUpStreak] = (consecutiveUp[currentUpStreak] || 0) + 1;
            }
            if (currentDownStreak > 1) {
              consecutiveDown[currentDownStreak] = (consecutiveDown[currentDownStreak] || 0) + 1;
            }
            currentUpStreak = 0;
            currentDownStreak = 0;
          }
        }
        
        // 处理最后一组连续值
        if (currentUpStreak > 1) {
          consecutiveUp[currentUpStreak] = (consecutiveUp[currentUpStreak] || 0) + 1;
        }
        if (currentDownStreak > 1) {
          consecutiveDown[currentDownStreak] = (consecutiveDown[currentDownStreak] || 0) + 1;
        }
        
        // 返回统计数据
        return res.json({
          code: 0,
          data: {
            total: processedKlines.length,
            up: upCount,
            down: downCount,
            flat: flatCount,
            consecutive: {
              up: consecutiveUp,
              down: consecutiveDown
            },
            timeRange: {
              start: new Date(startTime).toISOString(),
              end: new Date(endTime).toISOString(),
              range: range
            }
          },
          msg: 'success'
        });
      } catch (error) {
        console.error('从币安API获取今天的数据失败:', error);
        // 如果币安API获取失败，返回空结果
        return res.json({
          code: 0,
          data: {
            total: 0,
            up: 0,
            down: 0,
            flat: 0,
            consecutive: { up: {}, down: {} },
            timeRange: {
              start: new Date(startTime).toISOString(),
              end: new Date(endTime).toISOString(),
              range: range
            }
          },
          msg: 'success'
        });
      }
    } else {
      // 非today范围，从缓存获取统计数据
      console.log(`从缓存获取统计数据(新API): ${symbol}, ${interval}, ${range}`);
      const stats = await statsCache.getStats(symbol, interval, range);

      res.json({
        code: 0,
        data: {
          ...stats,
          timeRange: {
            start: stats.timeRange.start,
            end: stats.timeRange.end,
            range: range
          }
        },
        msg: 'success'
      });
    }
  } catch (error) {
    console.error('获取K线统计数据失败:', error);
    res.status(500).json({
      code: 500,
      msg: '服务器内部错误',
      error: error.message
    });
  }
});

// 从数据库获取历史数据
router.get('/api/history', async (req, res) => {
    try {
        const { symbol, interval, startTime, endTime } = req.query;
        
        // 添加调试日志
        console.log('查询参数:', {
            symbol,
            interval,
            startTime,
            endTime
        });
        
        // 验证必需的参数
        if (!symbol || !interval || !startTime || !endTime) {
            return res.status(400).json({ error: '缺少必需的参数' });
        }
        
        // 判断时间范围是否在最近7天内
        const sevenDaysAgo = Date.now() - (7 * 24 * 60 * 60 * 1000);
        const requestStartTime = parseInt(startTime);
        
        // 如果请求的开始时间在7天内，直接从币安API获取数据
        if (requestStartTime >= sevenDaysAgo || range === '1w' || range === 'today' || range === 'yesterday') {
            console.log('请求的数据在7天内或选择了今天/昨天/最近1周选项，直接从币安API获取');
            
            try {
                // 调用币安API获取数据
                const binanceKlines = await binance.getKlines(
                    symbol, 
                    interval,
                    null,  // 不限制数量，币安会返回所有可用数据
                    requestStartTime,
                    parseInt(endTime)
                );
                
                if (!binanceKlines || binanceKlines.length === 0) {
                    return res.status(404).json({ error: '币安API未返回数据' });
                }
                
                console.log(`币安API返回 ${binanceKlines.length} 条数据`);
                
                // 币安API返回的数据格式与我们需要的格式不同，需要转换
                // 币安API返回的格式是：[开盘时间, 开盘价, 最高价, 最低价, 收盘价, 成交量, 收盘时间, 成交额, 成交笔数, 主动买入成交量, 主动买入成交额, 忽略]
                // 我们只需要直接返回即可
                return res.json(binanceKlines);
            } catch (error) {
                console.error('从币安API获取数据失败:', error);
                // 如果币安API获取失败，回退到数据库查询
                console.log('尝试从数据库获取数据...');
            }
        }
        
        // 从数据库获取数据
        console.log('请求的数据超过7天，从数据库获取');
        const connection = await pool.getConnection();
        
        try {
            // 处理10m周期的特殊情况
            const actualInterval = interval === '10m' ? '5m' : interval;
            
            // 查询数据库
            const [rows] = await connection.query(
                `SELECT * FROM kline_${actualInterval}_enhanced 
                 WHERE symbol = ? 
                 AND open_time >= ? 
                 AND open_time <= ? 
                 ORDER BY open_time ASC`,
                [symbol, requestStartTime, parseInt(endTime)]
            );
            
            // 添加调试日志
            console.log(`查询到 ${rows.length} 条数据`);
            
            if (rows.length === 0) {
                return res.status(404).json({ error: '未找到数据' });
            }
            
            // 转换数据格式为币安API格式
            const data = rows.map(row => [
                row.open_time.toString(),
                row.open_price.toString(),
                row.high_price.toString(),
                row.low_price.toString(),
                row.close_price.toString(),
                row.volume.toString(),
                row.close_time.toString(),
                row.quote_volume.toString(),
                row.trades_count.toString(),
                row.taker_buy_volume.toString(),
                row.taker_buy_quote_volume.toString()
            ]);
            
            // 处理10m周期的特殊情况
            if (interval === '10m') {
                console.log('处理10m周期数据，合并5m数据...');
                const mergedData = [];
                for (let i = 0; i < data.length - 1; i += 2) {
                    if (i + 1 < data.length) {
                        const k1 = data[i];
                        const k2 = data[i + 1];
                        if (parseInt(k2[0]) - parseInt(k1[0]) === 5 * 60 * 1000) {
                            mergedData.push([
                                k1[0],
                                k1[1],
                                Math.max(parseFloat(k1[2]), parseFloat(k2[2])).toString(),
                                Math.min(parseFloat(k1[3]), parseFloat(k2[3])).toString(),
                                k2[4],
                                (parseFloat(k1[5]) + parseFloat(k2[5])).toString(),
                                k2[6],
                                (parseFloat(k1[7]) + parseFloat(k2[7])).toString(),
                                (parseInt(k1[8]) + parseInt(k2[8])).toString(),
                                (parseFloat(k1[9]) + parseFloat(k2[9])).toString(),
                                (parseFloat(k1[10]) + parseFloat(k2[10])).toString()
                            ]);
                        }
                    }
                }
                
                console.log(`合成后得到 ${mergedData.length} 条10分钟K线数据`);
                res.json(mergedData);
            } else {
                res.json(data);
            }
        } finally {
            connection.release();
        }
    } catch (error) {
        console.error('获取历史数据失败:', error);
        res.status(500).json({ error: '服务器内部错误' });
    }
});

// 获取当前价格
router.get('/api/price', async (req, res) => {
    try {
        const { symbol = 'BTCUSDT' } = req.query;
        
        // 验证交易对
        if (!['BTCUSDT', 'ETHUSDT'].includes(symbol)) {
            return res.status(400).json({ error: '不支持的交易对' });
        }
        
        // 获取最新价格
        const url = `https://api.binance.com/api/v3/ticker/price?symbol=${symbol}`;
        console.log(`请求最新价格: ${url}`);
        
        const data = await getBinanceLatestPrice(symbol);
        
        if (!data || !data.price) {
            return res.status(500).json({ error: '获取价格失败' });
        }
        
        console.log(`获取到最新价格: ${data.price}`);
        
        res.json({
            code: 0,
            data: {
                symbol,
                price: data.price,
                time: new Date().toISOString()
            },
            msg: 'success'
        });
    } catch (error) {
        console.error('获取当前价格失败:', error);
        res.status(500).json({ error: '服务器内部错误' });
    }
});

// 获取时间间隔的毫秒数
function getIntervalMillis(interval) {
    const unit = interval.slice(-1);
    const value = parseInt(interval.slice(0, -1));
    
    switch (unit) {
        case 'm': return value * 60 * 1000;
        case 'h': return value * 60 * 60 * 1000;
        case 'd': return value * 24 * 60 * 60 * 1000;
        default: return 60 * 60 * 1000; // 默认1小时
    }
}

module.exports = router; 